package com.logistics.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.logistics.common.Constants;
import com.logistics.common.TenantContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * MyBatis-Plus 配置
 */
@Configuration
public class MyBatisPlusConfig {
    
    /**
     * 不需要租户隔离的表
     */
    private static final List<String> IGNORE_TENANT_TABLES = Arrays.asList(
        "platform_tenant",
        "subscription_order",
        "sys_user",       // 用户表通过 tenant_id 字段查询，但不自动注入
        "sys_dictionary", // 字典表由业务代码控制：支持平台预置(tenant_id=0)+租户自定义
        "sys_role"        // 角色表由业务代码控制：登录时需按用户tenantId+roleCode获取权限
    );
    
    /**
     * MyBatis-Plus 拦截器
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        
        // 1. 多租户拦截器
        TenantLineInnerInterceptor tenantInterceptor = new TenantLineInnerInterceptor();
        tenantInterceptor.setTenantLineHandler(new com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                // 从 ThreadLocal 获取租户ID
                Long tenantId = TenantContextHolder.getTenantId();
                if (tenantId == null) {
                    // 如果没有租户ID，返回平台租户ID
                    return new LongValue(Constants.PLATFORM_TENANT_ID);
                }
                return new LongValue(tenantId);
            }
            
            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }
            
            @Override
            public boolean ignoreTable(String tableName) {
                // 忽略不需要租户隔离的表
                return IGNORE_TENANT_TABLES.contains(tableName);
            }
        });
        interceptor.addInnerInterceptor(tenantInterceptor);
        
        // 2. 分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        
        return interceptor;
    }
}

